﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.ViewModels
{
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Windows.Media;

    using Chemistry.Models;
    using Chemistry.Tools;

    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;

    using MahApps.Metro.Controls.Dialogs;

    public class K3QuestionViewModel : VmBase
    {
        private IDialogCoordinator _dialogCoordinator;
        ProgressDialogController controller = null;

        private ImageSource _bursh;

        public ImageSource Header
        {
            get { return _bursh; }
            set { _bursh = value; RaisePropertyChanged("Header"); }
        }

        private Examinee _examinee;
        public Examinee Examinee
        {
            get { return _examinee; }
            set { _examinee = value; RaisePropertyChanged("Examinee"); }
        }

        private QuestionInfo _textQuestion;
        public QuestionInfo TextQuestion
        {
            get { return _textQuestion; }
            set { _textQuestion = value; RaisePropertyChanged("TextQuestion"); }
        }

        private ObservableCollection<OptionsInfo> _textOptions;
        public ObservableCollection<OptionsInfo> TextOptions
        {
            get { return _textOptions; }
            set { _textOptions = value; RaisePropertyChanged("TextOptions"); }
        }

        private QuestionInfo _imageQuestion;
        public QuestionInfo ImageQuestion
        {
            get { return _imageQuestion; }
            set { _imageQuestion = value; RaisePropertyChanged("ImageQuestion"); }
        }
        private ObservableCollection<OptionsInfo> _imageOptions;
        public ObservableCollection<OptionsInfo> ImageOptions
        {
            get { return _imageOptions; }
            set { _imageOptions = value; RaisePropertyChanged("ImageOptions"); }
        }

        private QuestionInfo _videoQuestion;
        public QuestionInfo VideoQuestion
        {
            get { return _videoQuestion; }
            set { _videoQuestion = value; RaisePropertyChanged("VideoQuestion"); }
        }
        private ObservableCollection<OptionsInfo> _videoOptions;
        public ObservableCollection<OptionsInfo> VideoOptions
        {
            get { return _videoOptions; }
            set { _videoOptions = value; RaisePropertyChanged("VideoOptions"); }
        }

        public List<SendQuestionOverAnswer> QuestionOverAnswers { get; set; }

        public K3QuestionViewModel()
        {
            CommitCommand = new RelayCommand(this.CommitExec);
             
            InitMessage();
        }
       

        private void InitMessage()
        {
            Register<K3ExamMessage>(this, MessageToken.K3BeginExaming,
                (i) =>
                    {
                        QuestionOverAnswers = new List<SendQuestionOverAnswer>();
                        InitQuestion(i);
                    });

            Register<SendQuestionOverAnswer>(
                this,
                MessageToken.K3GetOptions,
                (i) =>
                    {
                        i.QuestionId = this.TextQuestion.Id;
                        var textquesion = QuestionOverAnswers.SingleOrDefault(t => t.QuestionId == this.TextQuestion.Id);
                        if (textquesion != null)
                        {
                            if (textquesion.SelectAnswer != i.SelectAnswer)
                            {
                                QuestionOverAnswers.Remove(textquesion);
                                QuestionOverAnswers.Add(i);
                            }
                        }
                        else
                        {
                            QuestionOverAnswers.Add(i);
                        }
                    });

            Register<List<SendQuestionOverAnswer>>(this, MessageToken.K3GetOptions,
                (i) =>
                    {
                        if (i.Count == 0) return;
                        switch (i[0].QuestionType)
                        {
                            case EnumQuestionType.Image:
                                //移除之前的答案，然后添加新选项
                                var image_answers = QuestionOverAnswers.Where(t => t.QuestionId == ImageQuestion.Id).ToList();
                                foreach (var item in image_answers)
                                {
                                    QuestionOverAnswers.Remove(item);
                                }
                                i.ForEach(a=>a.QuestionId = ImageQuestion.Id);
                                QuestionOverAnswers.AddRange(i);
                                break;
                            case EnumQuestionType.Video:
                                //移除之前的答案，然后添加新选项
                                var video_answers = QuestionOverAnswers.Where(t => t.QuestionId == VideoQuestion.Id).ToList();
                                foreach (var item in video_answers)
                                {
                                    QuestionOverAnswers.Remove(item);
                                }
                                i.ForEach(a => a.QuestionId = VideoQuestion.Id);
                                QuestionOverAnswers.AddRange(i);
                                break;
                        }
                        

                    });
        }

        private void InitQuestion(K3ExamMessage message)
        {
            ImageSourceConverter converter = new ImageSourceConverter();
            Header = (ImageSource)converter.ConvertFrom(message.Examinee.Pictrue);

            Examinee = message.Examinee;

            var imageQuestion = message.QuestionInfoes.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Image);
            if (imageQuestion != null)
            {
                var imageOptions = message.OptionsInfoes.Where(t => t.QuestionID == imageQuestion.Id).ToList();
                if (imageOptions.Count > 0) this.ImageOptions = new ObservableCollection<OptionsInfo>(imageOptions);
                this.ImageQuestion = imageQuestion;
            }

            var textQuestion = message.QuestionInfoes.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Text);
            if (textQuestion != null)
            {
                var textOptions = message.OptionsInfoes.Where(t => t.QuestionID == textQuestion.Id).ToList();
                if (textOptions.Count > 0) this.TextOptions = new ObservableCollection<OptionsInfo>(textOptions);
                this.TextQuestion = textQuestion;
            }

            var videoQuestion = message.QuestionInfoes.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Video);
            if (videoQuestion != null)
            {
                var videoOptions = message.OptionsInfoes.Where(t => t.QuestionID == videoQuestion.Id).ToList();
                if (videoOptions.Count > 0) this.VideoOptions = new ObservableCollection<OptionsInfo>(videoOptions);
                this.VideoQuestion = videoQuestion;
            }
        }

        private async void CommitExec()
        {
            if (MessageBox.Show("确认要交卷吗？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question)
                != MessageBoxResult.OK) return;

            int allScrore = 0;
            var text = QuestionOverAnswers.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Text);
            var textScore = (text != null && _textQuestion != null && text.SelectAnswer == _textQuestion.Answer.ToUpper()) ? 6 : 0;

            var images = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Image).Select(i => i.SelectAnswer).ToList();
            var image_answers = string.Join("", images);
            var image_socre = image_answers == _imageQuestion.Answer.ToUpper() ? 6 : 0;

            var videos = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Video).Select(i => i.SelectAnswer).ToList();
            var video_answers = string.Join("", videos);
            var video_score = video_answers == _videoQuestion.Answer.ToUpper() ? 8 : 0;

           //var result = await UploadScore(textScore, image_socre, video_score);
            //if (result)
            if(true)
            {
                MessageBox.Show("上传完成", "上传成绩", MessageBoxButton.OK);
                Send(MessageToken.K3ExamingOver);
            }


        }

        private void ResetData()
        {
            
        }

        private async Task<bool> UploadScore(int textScore, int imageScore, int videoScore)
        {
            bool issuccess = false;
            var allScrore = textScore + imageScore + videoScore;
            ScoreData data = new ScoreData()
            {
                session = HttpBasePrimary.Session,
                nr = this.Examinee.TicketId,
                items = new List<Score>(){
                        new Score(){ name = "xc_1_"+_textQuestion.Content, value=textScore},
                        new Score(){ name = "xc_2_"+_imageQuestion.Content, value=imageScore},
                        new Score(){ name = "xc_3_"+_videoQuestion.Content, value=videoScore}, 
                        new Score(){ name = "xc_sum", value=allScrore}, 
                   }
            };
            try
            {
                var rdata = await HttpBasePrimary.PostAsJsonAsync<ResultData>("Score", data);
                string log_msg = string.Format("考生{0}上传分数，返回值{1}", Examinee.TicketId, rdata.status);

                LogTool.WriteInfoLog(log_msg);

                string message = String.Empty;
                switch (rdata.status)
                {
                    case 0:
                        message = string.Format("上传成绩完成, 得分：{0}", allScrore);
                        issuccess = true;
                        break;
                    case -1:
                        message="身份验证失败，请尝试重录系统";
                        break;
                    case -2:
                        message="参数异常";
                        break;
                    case -3:
                        message="服务器内部错误，请联系管理员";
                        break;
                    case 2:
                        message="未知的分数项代码";
                        break;
                }
                MessageBox.Show(message, "上传成绩", MessageBoxButton.OK);
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
                MessageBox.Show("上传过程中遇到错误，请确认网络畅通", "上传成绩", MessageBoxButton.OK);
                
            }
            return issuccess;
        }
    }
}
